//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON
import WCDBSwift

class MemberQuitHandler: NoticeHandlerProtocol {
    static let instance = MemberQuitHandler()

    private init() {
    }

    private let queue = DispatchQueue(label: "com.tst.db",qos:.background)

    func handler(_ msg: Message) {
        do {
            let db = SQLiteHelper.getDb()
            try db.run(transaction: { _ in
//                let json = JSON(parseJSON: msg.content ?? "")
                if let groupMember = try GroupDao.getMember(msg.sessionServerId, userId: msg.userId) {
                    groupMember.deleted = true
                    groupMember.memberType = .normal
                    try db.update(table: GroupMember.table,
                            on: [GroupMember.CodingKeys.deleted,GroupMember.CodingKeys.memberType],
                            with: groupMember,
                            where: GroupMember.CodingKeys.id == groupMember.id)
                }
            })
            try GroupService().getGroupInfoFromRemote(msg.sessionServerId,queue:queue)
        } catch {
            print(error)
        }
    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let contact = try ContactDao.getContact(msg.from)
            let groupMember = try GroupDao.getMember(msg.sessionId, userId: msg.from)

            let json = JSON(parseJSON: msg.text ?? "")

            var name = contact?.remarkName ?? groupMember?.nickName ?? contact?.name
            if msg.isMe {
                name = "你"
            }
            return "\(name ?? "陌生人" ) 退出了本群"

        } catch {
            return msg.text
        }
    }
}
